package com.zlx.sharelive.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.softpal.locationutils.LocationUtils;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseInfoBean;
import com.zlx.module_base.base_api.res_data.UserAddressUp;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.StringUt;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.fragment.CommunityFg;
import com.zlx.sharelive.fragment.HomeFg;
import com.zlx.sharelive.fragment.MessageFg;
import com.zlx.sharelive.fragment.MyFg;
import com.zlx.sharelive.fragment.ShortVideoFg;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

/**
 * 首页
 */
public class MainAc extends BaseAc implements AMapLocationListener {

    @BindView(R.id.tv_home_1)
    TextView tv_home_1;
    @BindView(R.id.tv_home_2)
    TextView tv_home_2;
    @BindView(R.id.tv_home_4)
    TextView tv_home_4;
    @BindView(R.id.tv_home_5)
    TextView tv_home_5;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    private List<BaseFg> mFragment = new ArrayList<>();
    private int[] tab1 = {R.mipmap.home_top1_1, R.mipmap.home_top2_1, R.mipmap.home_top3_1, R.mipmap.home_top4_1};
    private int[] tab2 = {R.mipmap.home_top1_2, R.mipmap.home_top2_2, R.mipmap.home_top3_2, R.mipmap.home_top4_2};
    private List<TextView> mTextViewList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);

        try {
            mlocationClient = new AMapLocationClient(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_main;
    }


    @Override
    public void initViews() {
        super.initViews();

        mTextViewList.clear();
        mTextViewList.add(tv_home_1);
        mTextViewList.add(tv_home_2);
        mTextViewList.add(tv_home_4);
        mTextViewList.add(tv_home_5);
        initFragment();

        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initLocation();
        loginIm();
        getBaseInfo();
    }

    /**
     * 用户基本信息
     */
    private void getBaseInfo() {
        ApiUtil.getUserApi().getBaseInfo(SPUtil.getToken(this)).
                observe(this, new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<BaseInfoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseInfoBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (null != data.getData().getInfo()) {
                                            if (data.getData().getInfo().size() > 0) {
                                                setInfo(data.getData().getInfo().get(0));
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();

                            }
                        }));
    }

    private void setInfo(BaseInfoBean.InfoDTO data) {
        if (!StringUt.isEmpty(data.getId()) && !StringUt.isEmpty(data.getNickname()) && !StringUt.isEmpty(data.getAvatar())) {
            UserInfo userInfo = new UserInfo(data.getId(), data.getNickname(), Uri.parse(data.getAvatar()));
            RongIM.getInstance().refreshUserInfoCache(userInfo);
        }
    }

    private void loginIm() {
        String imToken = (String) SPUtil.get(this, Constants.SP_IM_TOKEN, "");

        RongIMClient.connect(imToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus code) {
                //消息数据库打开，可以进入到主页面
                Log.d("ret", "joker   登录成功IM1");
            }

            @Override
            public void onSuccess(String s) {
                //连接成功
                Log.d("ret", "joker   登录成功IM2");
//                startActivity(new Intent(MainAc.this, MainAc.class));
//                finish();
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode errorCode) {
                if (errorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_INCORRECT)) {
                    //从 APP 服务获取新 token，并重连
                    Log.d("ret", "joker   登录失败1" + errorCode);
                } else {
                    //无法连接 IM 服务器，请根据相应的错误码作出对应处理
                    Log.d("ret", "joker   登录失败2" + errorCode);
                }
            }
        });
    }

    private void initLocation() {
        Location location = LocationUtils.getMyLocation(MainAc.this);
        UserAddressUp userAddressUp = new UserAddressUp();
        userAddressUp.setLat(location.getLatitude() + "");
        userAddressUp.setLng(location.getLongitude() + "");

        ApiUtil.getServiceApi().getUserAddress(SPUtil.getToken(MainAc.this),
                userAddressUp).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<String>>() {
            @Override
            public void onSuccess(ApiResponse<String> data) {

            }
        }));
    }

    private void initFragment() {
        mFragment.clear();
        mFragment.add(new HomeFg());
        mFragment.add(new CommunityFg());
        mFragment.add(new MessageFg());
        mFragment.add(new MyFg());
        mFragment.add(new ShortVideoFg());
        commitAllowingStateLoss(0);
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragment.get(position);
            transaction.add(R.id.frameLayout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏所有Fragment
     */
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragment.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    @OnClick({R.id.tv_home_1, R.id.tv_home_2, R.id.tv_home_3, R.id.tv_home_4, R.id.tv_home_5})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_home_1:
                commitAllowingStateLoss(0);
                setTextColor(0);
                break;
            case R.id.tv_home_2:
                commitAllowingStateLoss(1);
                setTextColor(1);
                break;
            case R.id.tv_home_3:
                //短视频
                commitAllowingStateLoss(4);
                setTextColor(4);
                break;
            case R.id.tv_home_4:
                //我的
                if (null != SPUtil.getObjectFromShare(MainAc.this,
                        Constants.USERINFO)) {
                    commitAllowingStateLoss(2);
                    setTextColor(2);
                } else {
                    startActivity(new Intent(MainAc.this, LoginAc.class));
                }
                break;
            case R.id.tv_home_5:
                if (null != SPUtil.getObjectFromShare(MainAc.this,
                        Constants.USERINFO)) {
                    commitAllowingStateLoss(3);
                    setTextColor(3);
                } else {
                    startActivity(new Intent(MainAc.this, LoginAc.class));
                }
                break;
        }
    }

    public void setTextColor(int position) {
        if (position == mTextViewList.size()) {
            for (int i = 0; i < mTextViewList.size(); i++) {
                Drawable top = getResources().getDrawable(tab2[i]);
                mTextViewList.get(i).setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
                mTextViewList.get(i).setTextColor(getResources().getColor(R.color.martini));
            }
        } else {
            for (int i = 0; i < mTextViewList.size(); i++) {
                if (position == i) {
                    Drawable top = getResources().getDrawable(tab1[position]);
                    mTextViewList.get(position).setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
                    mTextViewList.get(position).setTextColor(getResources().getColor(R.color.black));
                } else {
                    Drawable top = getResources().getDrawable(tab2[i]);
                    mTextViewList.get(i).setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
                    mTextViewList.get(i).setTextColor(getResources().getColor(R.color.martini));
                }
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                String street = amapLocation.getStreet();
                String city = amapLocation.getCity();
                SPUtil.put(this, Constants.SP_CITY, city);
                SPUtil.put(this, Constants.SP_STREET, street);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
//                zhoubian();
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }
}
